package cn.ac.iie.di.ban.ycl.idgen;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Hex;

public class IDSHAGeneratorImpl implements IDGeneratorInterface {

    @Override
    public String getId(String _ch, String _spec, String asp, String adp, String _key) throws Exception {
        if (_ch == null || _ch.isEmpty() || _spec == null || _spec.isEmpty()
                || _key == null || _key.isEmpty()) {
            throw new Exception("_ch _spec _key 不能为空");
        }

        if ((asp == null || asp.isEmpty()) && (adp == null || adp.isEmpty())) {
            throw new Exception("asp 与 adp 不能同时为空");
        }

        StringBuffer _id = new StringBuffer();
        _id = _id.append(_ch);
        _id = _id.append(_spec);
        _id = _id.append("_");

        if (asp == null) {
            asp = "";
        }

        if (adp == null) {
            adp = "";
        }

        if (!asp.isEmpty()) {
            if (asp.equals(adp)) {
                _id = _id.append(asp);
            } else {
                _id = _id.append(asp).append("_").append(adp);
            }
        } else {
            _id = _id.append(asp).append("_").append(adp);
        }

        _id = _id.append("_");
        if (_key.length() < 64) {
            _id = _id.append(_key);
        } else {
            String sha = SHA256(_key);
            if (sha != null) {
                _id = _id.append(sha);
            } else {
                return null;
            }

        }
        return _id.toString();
    }

    public static String SHA256(String source) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(source.getBytes("UTF-8"));
        return Hex.encodeHexString(hash);
    }
}
